export function openDB(name, version = 1) {
  return new Promise((resolve, reject) => {
    const request = window.indexedDB.open(name, version)
    request.onerror = (err) => {
      reject('打开失败', err)
    }
    request.onsuccess = (event) => {
      resolve(event.target.result)
    }
    request.onupgradeneeded = (event) => {
      const db = event.target.result
      db.createObjectStore('index', { keyPath: 'name' })
    }
  })
}
// 存数据
export function pushData(dbName, tableName, data) {
  console.log('插入数据')
  return new Promise((resolve, reject) => {
    openDB(dbName).then((db) => {
      const transaction = db.transaction(tableName, 'readwrite')
      transaction.objectStore(tableName).add(data)
      transaction.oncomplete = () => {
        resolve('success')
      }
      transaction.onerror = () => {
        reject('fail')
      }
    })
  })
}
// 获取数据
export async function readData(dbName, tableName, key) {
  return new Promise((resolve, reject) => {
    openDB(dbName)
      .then((res) => {
        const mid = res.transaction(tableName).objectStore(tableName).get(key)
        mid.onsuccess = (event) => {
          resolve(event.target.result)
        }
      })
      .catch(() => {
        reject('获取失败')
      })
  })
}
// 删除数据
export async function delData(dbName, tableName, key) {
  return new Promise((resolve) => {
    openDB(dbName).then((res) => {
      res
        .transaction(tableName, 'readwrite')
        .objectStore(tableName)
        .delete(key).onsuccess = () => {
          resolve('删除成功')
        }
    })
  })
}
// 更新数据
export async function updateData(dbName, tableName, key, data) {
  return new Promise((resolve, reject) => {
    openDB(dbName).then((res) => {
      const objectStore = res
        .transaction(tableName, 'readwrite')
        .objectStore(tableName)
      const request = objectStore.get(key)
      request.onerror = () => {
        reject('获取数据失败')
      }
      request.onsuccess = () => {
        const requestUpdate = objectStore.put(data)
        requestUpdate.onerror = () => {
          reject('保存失败')
        }
        requestUpdate.onsuccess = () => {
          resolve('更新成功')
        }
      }
    })
  })
}
